import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';

export default class UserListViewProvider implements vscode.WebviewViewProvider {

    public static readonly viewType = 'userList.contentView1';
    private _indexFilePath: string = 'dist/index.html';

    private _view?: vscode.WebviewView;
    private mExtensionContext:vscode.ExtensionContext;
    private mPort;
    private mUrl;


    constructor(private readonly _extensionUri: vscode.Uri, context: vscode.ExtensionContext, port: number) {
        this.mExtensionContext = context;
        this.mPort = port;
        this.mUrl = `http://localhost:${port}`;
    }

    public resolveWebviewView(
        webviewView: vscode.WebviewView,
        context: vscode.WebviewViewResolveContext,
        _token: vscode.CancellationToken) {
        this._view = webviewView;

        webviewView.webview.options = {
            // Allow scripts in the webview
            enableScripts: true,

            localResourceRoots: [
                this._extensionUri
            ]
        };

        // webviewView.webview.html = this.getWebviewContent(this.mUrl);
        // console.log("======xx====extensionPath:",this.mExtensionContext.extensionPath)

        webviewView.webview.html = this.getHtmlForWebview();


        webviewView.onDidChangeVisibility(l => {
                webviewView.webview.html = this.getWebviewContent(this.mUrl);
        })
    }

    public getHtmlForWebview(): string {
        let htmlPath = path.join(this.mExtensionContext.extensionPath, this._indexFilePath);
        let html = fs.readFileSync(htmlPath, 'utf-8');
        // vscode不支持直接加载本地资源，设置baseUrl为插件目录
        html = html.replace(
            "<head>",
            `<head><base href="${vscode.Uri.file(
                path.join(this.mExtensionContext.extensionPath, "dist")
            ).with({scheme: "vscode-resource"})}/"></base>`
        );
        console.log(html);
        return html;
    }

    private getWebviewContent(url: string) {
        url = `http://localhost:${this.mPort}#/index`;
        console.log("==========html url:",url)
        let testValue = `D:\\work\\code\\temp\\lty-plugin-lvgl\\dist\\index.html`

        return `<!DOCTYPE html>
                <html lang="en">
                <head>
                    <meta charset="UTF-8">
                </head>
                <body style="padding: 0">
                <div style="height: 100vh; width: 100%">
                    <iframe id="mIframe" style="width: 100%;height: 100%" src="${testValue}" frameborder="0"></iframe>
                </div>
                <!--    <img src="https://media.giphy.com/media/JIX9t2j0ZTN9S/giphy.gif" width="300" />-->
                </body>
                </html>`;
    }
}
